import { usePermissions } from '@/store/userStore.ts';
import { AppRouteObject } from '#/router.ts';
import { useMemo } from 'react';

function filterRoutesByPermissions(
  routes: AppRouteObject[],
  permissions: string[],
): AppRouteObject[] {
  // 递归处理 routes
  const filterRoute = (route: AppRouteObject): AppRouteObject | null => {
    const { meta, children } = route;

    // 检查 meta.permissions 是否存在以及是否所有权限都在 permissions 列表中
    const hasPermissions =
      !meta?.permissions || meta.permissions.every((p) => permissions.includes(p));

    // 如果当前路由符合条件，检查 children
    if (hasPermissions) {
      let filteredChildren: AppRouteObject[] | undefined;

      // 递归检查子路由
      if (children) {
        filteredChildren = children.map(filterRoute).filter(Boolean) as AppRouteObject[];
      }

      // 返回符合条件的路由，同时保留已筛选的 children
      return {
        ...route,
        children: filteredChildren,
      };
    }

    // 不符合条件，返回 null
    return null;
  };

  // 过滤 routes
  return routes.map(filterRoute).filter(Boolean) as AppRouteObject[];
}

export const usePermissionRoutes = (routes: AppRouteObject[]) => {
  const permissions = usePermissions();

  return useMemo(() => {
    return filterRoutesByPermissions(routes, permissions);
  }, [permissions, routes]);
};
